var gulp = require('gulp')

// 引入插件
var uglify = require('gulp-uglify')
var cssmin = require('gulp-cssmin')
var sass = require('gulp-sass')
var htmlmin = require('gulp-htmlmin')
var watch = require('gulp-watch')
var webserver = require('gulp-webserver')

// 开启任务
gulp.task('js', function () {
    // 文件源
    gulp.src('src/js/*.js')
        // 执行压缩
        .pipe(uglify())
        // 导出文件
        .pipe(gulp.dest('dist/js/'))
})

gulp.task('css', function () {
    gulp.src('src/css/*.css')
        .pipe(cssmin())
        .pipe(gulp.dest('dist/css/'))
})

gulp.task('sass', function () {
    gulp.src('src/css/*.scss')
        .pipe(sass())
        .pipe(cssmin())
        .pipe(gulp.dest('dist/css/'))
})

gulp.task('html', function () {
    gulp.src('src/page/*.html')
        .pipe(htmlmin({
            removeComments: true,  //清除HTML注释
            collapseWhitespace: true,  //压缩HTML
            collapseBooleanAttributes: true,  //省略布尔属性的值 <input checked="true"/> ==> <input checked />
            removeEmptyAttributes: true,  //删除所有空格作属性值 <input id="" /> ==> <input />
            // removeScriptTypeAttributes: true,  //删除<script>的type="text/javascript"
            // removeStyleLinkTypeAttributes: true,  //删除<style>和<link>的type="text/css"
            minifyJS: true,  //压缩页面JS
            minifyCSS: true  //压缩页面CSS
        }))
        .pipe(gulp.dest('dist/page/'))
})

gulp.task('watch', function () {
    watch('src/css/', function () {
        gulp.start('css')
        gulp.start('sass')
    })
    watch('src/page/', function () {
        gulp.start('html')
    })
    watch('src/js/', function () {
        gulp.start('js')
    })
})

gulp.task('webserver', function () {
    gulp.src('dist')
        .pipe(webserver({
            livereload: true,       // 热更新
            open: 'page/index.html',    // 默认打开地址
            host: 'localhost',      // 主机域名地址
            port: 3000,          // 端口
            proxies: [
                {
                    source: '/login',
                    target: 'http://localhost:8080/index'
                },
                {
                    source: '/list',
                    target: 'http://localhost:8080/list'
                },
            ]
        }));
})

// 开启默认任务
// 执行任务
gulp.task('default', ['js', 'css', 'sass', 'html', 'watch', 'webserver'], function () {
    // console.log('ok')
})